package org.dromara.assets.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.binance.api.client.BinanceApiCallback;
import com.binance.api.client.domain.account.Order;
import com.binance.api.client.domain.event.OrderTradeUpdateEvent;
import com.binance.api.client.domain.event.UserDataUpdateEvent;
import org.dromara.assets.biz.AssetsTradeRecordServiceBiz;
import org.dromara.assets.service.IAssetsTradeRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class BinanceWebSocketCallback implements BinanceApiCallback<UserDataUpdateEvent> {

    @Autowired
    private AssetsTradeRecordServiceBiz assetsTradeRecordServiceBiz;

    @Override
    public void onResponse(UserDataUpdateEvent response) {
        log.info("receive msg:{}",response);
        switch (response.getEventType()) {
            case ORDER_TRADE_UPDATE:
                OrderTradeUpdateEvent event = response.getOrderTradeUpdateEvent();
                log.info("订单更新消息：{}", response.getOrderTradeUpdateEvent());
                Order order = new Order();
                BeanUtil.copyProperties(event, order, true);
                order.setStatus(event.getOrderStatus());
                order.setExecutedQty(event.getAccumulatedQuantity());
                order.setCummulativeQuoteQty(event.getCumulativeQuoteQty());
                order.setOrigQty(event.getOriginalQuantity());
                order.setTime(event.getOrderCreationTime());
                order.setUpdateTime(event.getOrderTradeTime());
                //判断订单状态，为终态才处理
                if (AssetsTradeRecordServiceBiz.finalState.contains(order.getStatus().toString())) {
                    assetsTradeRecordServiceBiz.syncItem(order.getSymbol(), order, Long.parseLong("4"));
                }
                break;
            case BALANCE_UPDATE:
                log.info("账户余额更新：{}", response.getBalanceUpdateEvent().getAsset());
                break;
            default:
                log.info("其他事件类型：{}", response.getEventType());
                break;
        }
    }
}
